package com.xb.loan.admin.web.controller;

import com.xb.loan.util.log.DefaultLoggerFacotry;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
@Controller
public class MainController extends BaseController {
	private Logger logger = DefaultLoggerFacotry.getLogger(MainController.class);

	
	@RequestMapping("/main")
    public String main(Model model,RedirectAttributes rAttr,HttpServletRequest request) {
    	/*// 今天实时汇总 start
    	Map<String, Object> sumTodayResult = mainService.sumTodayResult();
    	model.addAttribute("sumTodayResult", sumTodayResult);
    	// 今天实时汇总 end
    	
    	Calendar c = Calendar.getInstance();
		String endDate = FormatOperation.formatDateToYMD(c.getTime());
		c.set(Calendar.DAY_OF_MONTH, 1);
		String startDate = FormatOperation.formatDateToYMD(c.getTime());
		statMonthData(model, startDate, endDate);
    	// 格式化首页金额
		formatMainMoney(model);
		
		// 是否显示大奖通知框
		HttpSession session = request.getSession();
        model.addAttribute(Show_Prize_Notice, session.getAttribute(Show_Prize_Notice));  */
		// 是否显示大奖通知框
        this.getLoginUserType(request, model);
		
        return "main";
    }
	/*
	@SuppressWarnings("unchecked")
	private void formatMainMoney(Model model){
		Map<String, Object> result = model.asMap();
		
		// 格式化今天实时汇总
		Map<String, Object> sumTodayResult = (Map<String, Object>) result.get("sumTodayResult");
		sumTodayResult.put("sale", FormatOperation.formatMoney((double)sumTodayResult.get("sale")));
		sumTodayResult.put("prize", FormatOperation.formatMoney((double)sumTodayResult.get("prize")));
		sumTodayResult.put("partnerCharge", FormatOperation.formatMoney((double)sumTodayResult.get("partnerCharge")));
		sumTodayResult.put("userCharge", FormatOperation.formatMoney((double)sumTodayResult.get("userCharge")));
		sumTodayResult.put("partnerEncash", FormatOperation.formatMoney((double)sumTodayResult.get("partnerEncash")));
		sumTodayResult.put("userEncash", FormatOperation.formatMoney((double)sumTodayResult.get("userEncash")));
		model.addAttribute("sumTodayResult", sumTodayResult);
		
		// 格式化当月中奖汇总
		List<Map<String, Object>> prizeGroupByGame = (List<Map<String, Object>>) result.get("prizeGroupByGame");
		for(int i = 0; i < prizeGroupByGame.size(); i++){
			Map<String, Object> prize = prizeGroupByGame.get(i);
			prize.put("smallTicketSum", FormatOperation.formatMoney((double)prize.get("smallTicketSum")));
			prize.put("bigTicketSum", FormatOperation.formatMoney((double)prize.get("bigTicketSum")));
		}
		model.addAttribute("prizeGroupByGame", prizeGroupByGame);
		
		Map<String, Object> sumPrize = (Map<String, Object>) result.get("sumPrize");
		sumPrize.put("smallTicketSum", FormatOperation.formatMoney((double)sumPrize.get("smallTicketSum")));
		sumPrize.put("bigTicketSum", FormatOperation.formatMoney((double)sumPrize.get("bigTicketSum")));
		model.addAttribute("sumPrize", sumPrize);
	}

	private void statMonthData(Model model, String startDate, String endDate) {
		List<Map<String, Object>> sumStatSaleGroupByGame = mainService.sumStatSaleGroupByGame(null, startDate, endDate);
		// 本月销量，按彩种分组 start
		List<Map<String, Object>> saleGroupByGameList = new LinkedList<Map<String,Object>>();
		List<Map<String, Object>> prizeGroupByGame = new LinkedList<Map<String,Object>>();
		Map<String, Object> sumPrize = new HashMap<String, Object>();
		for(int i = 0; i < sumStatSaleGroupByGame.size(); i++){
			Map<String, Object> statSale = sumStatSaleGroupByGame.get(i);
			// 销量统计--饼图
			Map<String, Object> saleGroupByGame = new HashMap<String, Object>();
			saleGroupByGame.put("name", statSale.get("gameId"));
			saleGroupByGame.put("y", ((double)statSale.get("sucTicketSum") / 10000.0));
			
			saleGroupByGameList.add(saleGroupByGame);
			// 中奖统计--表格
			prizeGroupByGame.add(statSale);
			Integer smallTicketNum = (Integer) sumPrize.get("smallTicketNum");
			sumPrize.put("smallTicketNum", (smallTicketNum == null ? 0 : smallTicketNum) + (Integer)statSale.get("smallTicketNum"));
			Double smallTicketSum = (Double) sumPrize.get("smallTicketSum");
			sumPrize.put("smallTicketSum", (smallTicketSum == null ? 0.0 : smallTicketSum) + (double)statSale.get("smallTicketSum"));
			Integer bigTicketNum = (Integer) sumPrize.get("bigTicketNum");
			sumPrize.put("bigTicketNum", (bigTicketNum == null ? 0 : bigTicketNum) + (Integer)statSale.get("bigTicketNum"));
			Double bigTicketSum = (Double) sumPrize.get("bigTicketSum");
			sumPrize.put("bigTicketSum", (bigTicketSum == null ? 0.0 : bigTicketSum) + (double)statSale.get("bigTicketSum"));
		}
		model.addAttribute("prizeGroupByGame", prizeGroupByGame);
		model.addAttribute("sumPrize", sumPrize);
		String saleGroupByGameJson = JsonUtils.toJson(saleGroupByGameList, false);
		model.addAttribute("saleGroupByGame", saleGroupByGameJson);
		// 本月销量，按彩种分组 end
		// 本月销量，按日期、彩种分组 start
		String allDay4MonthJson = JsonUtils.toJson(mainService.queryAllDay4Month(), false);
		model.addAttribute("allDay4Month", allDay4MonthJson);
		List<Map<String, Object>> sumStatSaleGroupByDayGame = mainService.sumStatSaleGroupByDayGame(startDate, endDate);
		List<Map<String, Object>> saleGroupByDayGame = new ArrayList<Map<String,Object>>();
		for(int i = 0; i < sumStatSaleGroupByDayGame.size(); i++){
			Map<String, Object> statSale = sumStatSaleGroupByDayGame.get(i);
			Map<String, Object> statSale4Show = findStatSale(saleGroupByDayGame, (String)statSale.get("gameId"));
			if(statSale4Show == null){
				statSale4Show = new HashMap<String, Object>();
				statSale4Show.put("name", statSale.get("gameId"));
				statSale4Show.put("data", new ArrayList<Double>());
				saleGroupByDayGame.add(statSale4Show);
			}
			@SuppressWarnings("unchecked")
			List<Double> data = (List<Double>) statSale4Show.get("data");
			data.add((Double) statSale.get("sucTicketSum") / 10000.0);
		}
		String saleGroupByDayGameJson = JsonUtils.toJson(saleGroupByDayGame, false);
		model.addAttribute("saleGroupByDayGame", saleGroupByDayGameJson);
		// 本月销量，按日期、彩种分组 end
	}

	private Map<String, Object> findStatSale(List<Map<String, Object>> saleGroupByDayGame, String string) {
		for(int i = 0; i < saleGroupByDayGame.size(); i++){
			if(string.equals(saleGroupByDayGame.get(i).get("name"))){
				return saleGroupByDayGame.get(i);
			}
		}
		return null;
	}

	@RequestMapping(value="/mainDetail/init", method=RequestMethod.GET)
	public String mainDetailInit(Model model) throws BizException{
		Calendar c = Calendar.getInstance();
		String startDate = FormatOperation.formatDateToY_M_D(c.getTime());
		model.addAttribute("startDate", startDate);
		model.addAttribute("endDate", startDate);
		this.getGames(model);
		return "mainDetail";
	}
	
	@RequestMapping(value="/mainDetail/query", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryMainDetail(HttpServletRequest request) throws BizException, ParseException{
		String startDateString = request.getParameter("startDate");
		String endDateString = request.getParameter("endDate");
		String gameId = request.getParameter("gameId");
		
		logger.info(LogFormatUtil.getFormatMsg(new String[]{"module", "gameId", "startDate", "endDate"}, 
				new Object[]{"Main", gameId, startDateString, endDateString}));
		
		Date startDate = null;
		Date endDate = null;
		if(startDateString != null){
			startDateString = startDateString.replaceAll("-", "");
			startDate = FormatOperation.formatStrToYMDHms14(startDateString + "000000");
		}
		if(endDateString != null){
			endDateString = endDateString.replaceAll("-", "");
			endDate = FormatOperation.formatStrToYMDHms14(endDateString + "235959");
		}
		
		if(!ok(startDate, endDate))
			return null;
		
		Map<String, Object> result = new HashMap<String, Object>();
		Calendar today = Calendar.getInstance();
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		result.put("dataList", dataList);
		
		Map<String, Double> sum = new HashMap<String, Double>();
		sum.put("sale", 0.0);
		sum.put("prize", 0.0);
		result.put("sum", sum);
		
		Map<String, Object> fund = new HashMap<String, Object>();
		fund.put("userCharge", 0.0);
		fund.put("partnerCharge", 0.0);
		fund.put("userEncash", 0.0);
		fund.put("partnerEncash", 0.0);
		
		result.put("fund", fund);
		
		if(endDate != null && endDate.after(today.getTime())){//截止日期 > 今天，查询实时数据
			today.add(Calendar.DAY_OF_MONTH, -1);
			endDateString = FormatOperation.formatDateToYMD(today.getTime());
			// 销量
			List<Map<String, Object>> saleList = mainService.sumTodaySale(gameId);
			for(int i = 0; i < saleList.size(); i++){
				Map<String, Object> sale = saleList.get(i);
				Map<String, Object> data = findDataMap(dataList, (String)sale.get("gameId"));
				if(data == null){
					data = new HashMap<String, Object>();
					data.put("gameId", sale.get("gameId"));
					dataList.add(data);
				}
				Double saleMoney = (Double) (data.get("sale") == null ? 0.0 :  data.get("sale"));
				data.put("sale", saleMoney + (double)sale.get("money"));
				// 汇总销量
				sum.put("sale", sum.get("sale") + (double)sale.get("money"));
			}
			// 奖额
			List<Map<String, Object>> prizeList = mainService.sumTodayPrize(gameId);
			for(int i = 0; i < prizeList.size(); i++){
				Map<String, Object> prize = prizeList.get(i);
				Map<String, Object> data = findDataMap(dataList, (String)prize.get("gameId"));
				if(data == null){
					data = new HashMap<String, Object>();
					data.put("gameId", prize.get("gameId"));
					dataList.add(data);
				}
				Double prizeMoney = (Double) (data.get("prize") == null ? 0.0 :  data.get("prize"));
				data.put("prize", prizeMoney + (double)prize.get("money"));
				// 汇总奖额
				sum.put("prize", sum.get("prize") + (double)prize.get("money"));
			}
			// 充值、提现
			mainService.sumTodayChargeEncash(fund);
		}
		if(startDate == null || endDate == null || startDate.compareTo(endDate) < 0) {// 开始日期 < 截止日期，查询历史数据
			List<Map<String, Object>> list = mainService.sumStatSaleGroupByGame(gameId, startDateString, endDateString);
			for(int i = 0; i < list.size(); i++){
				Map<String, Object> map = list.get(i);
				Map<String, Object> data = findDataMap(dataList, (String)map.get("gameId"));
				if(data == null){
					data = new HashMap<String, Object>();
					data.put("gameId", map.get("gameId"));
					dataList.add(data);
				}
				Double saleMoney = (Double) (data.get("sale") == null ? 0.0 :  data.get("sale"));
				data.put("sale", saleMoney + (double)map.get("sucTicketSum"));
				// 汇总销量
				sum.put("sale", sum.get("sale") + (double)map.get("sucTicketSum"));
				
				Double prizeMoney = (Double) (data.get("prize") == null ? 0.0 :  data.get("prize"));
				data.put("prize", prizeMoney + (double)map.get("bigTicketSum") + (double)map.get("smallTicketSum"));
				// 汇总奖额
				sum.put("prize", sum.get("prize") + (double)map.get("bigTicketSum") + (double)map.get("smallTicketSum"));
			}
			// 充值
			List<Map<String, Object>> historyCharge = mainService.queryHistoryCharge(startDateString, endDateString);
			if(historyCharge != null && historyCharge.size() > 0){
				for(Map<String, Object> map : historyCharge){
					if((int)map.get("userLevel") == UserLevel.CHANNEL.getCode())
						fund.put("partnerCharge", (double)map.get("totalSucMoney") + (double)fund.get("partnerCharge"));
					else
						fund.put("userCharge", (double)map.get("totalSucMoney") + (double)fund.get("userCharge"));
				}
			}
			// 提现
			List<Map<String, Object>> historyEncash = mainService.queryHistoryEncash(startDateString, endDateString);
			if(historyEncash != null && historyEncash.size() > 0){
				for(Map<String, Object> map : historyEncash){
					if((int)map.get("userLevel") == UserLevel.CHANNEL.getCode())
						fund.put("partnerEncash", (double)map.get("totalSucMoney") + (double)fund.get("partnerEncash"));
					else
						fund.put("userEncash", (double)map.get("totalSucMoney") + (double)fund.get("userEncash"));
				}
			}
		}
		
		// 显示彩种名称
		for(int i = 0; i < dataList.size(); i++){
			Map<String, Object> data = dataList.get(i);
			data.put("gameName", gameService.selectByGameId((String) data.get("gameId")).getGameName());
		}
		
		return result;
	}

	private Map<String, Object> findDataMap(List<Map<String, Object>> dataList, String gameId) {
		for(Map<String, Object> map : dataList){
			if(gameId.equals(map.get("gameId")))
				return map;
		}
		return null;
	}

	private boolean ok(Date startDate, Date endDate) {
		if(startDate == null || endDate == null)
			return true;
		// 开始日期>截止日期
		if(startDate.compareTo(endDate) > 0)
			return false;
		Calendar today = Calendar.getInstance();
		today.set(Calendar.HOUR_OF_DAY, 23);
		today.set(Calendar.MINUTE, 59);
		today.set(Calendar.SECOND, 59);
		// 开始日期>今天
		if(startDate.compareTo(today.getTime()) > 0)
			return false;
		return true;
	}
	
	@RequestMapping(value="/mainDetail/export", method=RequestMethod.GET)
	public void exportMainDetail(HttpServletRequest request, HttpServletResponse response) throws BizException, IOException, ParseException{
		Map<String, Object> result = queryMainDetail(request);
		//文件目录名
        String nowTime = "数据汇总" + getNowTime();
        //生成csv文件
        String csvFileFolder = makeCSVFile(nowTime, result);
        //压缩csv文件称zip
        String zipFilepath = makeZipFile(nowTime, csvFileFolder);
        csvDownLoad(nowTime, zipFilepath, csvFileFolder, response);
	}

	@SuppressWarnings("unchecked")
	private String makeCSVFile(String nowTime, Map<String, Object> result) throws IOException {
		List<Map<String, Object>> dataList = (List<Map<String, Object>>) result.get("dataList");
		for (Map<String, Object> map : dataList) {
			map.put("sale", formatNum(map.get("sale").toString()));
			map.put("prize", formatNum(map.get("prize").toString()));
			String gameId = (String) map.get("gameId");
			if(null!=gameId && !"".equals(gameId)){
				map.put("gameId", gameService.selectByGameId(gameId).getGameName());
			}
			
		}
		String partnerCharge = ((Map<String, Double>)result.get("fund")).get("partnerCharge").toString();
		String userCharge = ((Map<String, Double>)result.get("fund")).get("userCharge").toString();
		String partnerEncash = ((Map<String, Double>)result.get("fund")).get("partnerEncash").toString();
		String userEncash = ((Map<String, Double>)result.get("fund")).get("userEncash").toString();
		for(int i = 0; i < dataList.size(); i++){
			dataList.get(i).put("partnerCharge", formatNum(partnerCharge));
			dataList.get(i).put("userCharge", formatNum(userCharge));
			dataList.get(i).put("partnerEncash", formatNum(partnerEncash));
			dataList.get(i).put("userEncash", formatNum(userEncash));
		}
		
		String header = "序号,彩种,销量总额,中奖总额,渠道充值总额,彩民充值总额,渠道提现总额,彩民提现总额";
		//返回的列表的列名
		FieldName[] fieldName = new FieldName[] {
				new FieldName("gameId", false), 
				new FieldName("sale", true),
				new FieldName("prize", true),
				new FieldName("partnerCharge", false),
				new FieldName("userCharge", false),
				new FieldName("partnerEncash", false),
				new FieldName("userEncash", false)};
		String csvFileFolder = writeCSVFile(nowTime, header, fieldName, dataList, true, true);
		return csvFileFolder;
	}
	
	@RequestMapping(value="/main/closePrizeNotice", method=RequestMethod.POST)
	public Map<String, Object> closePrizeNotice(HttpServletRequest request){
		HttpSession session = request.getSession();
        session.setAttribute(Show_Prize_Notice, "false");
        return null;
	}8*/
	
	private String formatNum(String num){
		DecimalFormat df=new DecimalFormat("0.00");
		num=df.format(Double.parseDouble(num));
		return num;
	}
	
}
